package com.fiberhome.nas.core.database.datasource

import com.fiberhome.nas.core.database.dao.UploadTaskDao
import com.fiberhome.nas.core.database.entity.UploadTaskEntity
import com.fiberhome.nas.core.model.entity.UploadTask
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import javax.inject.Inject
import javax.inject.Singleton

/**
 * 任务中心数据源
 * 负责任务中心相关的数据库操作
 */
@Singleton
class UploadTaskDataSource @Inject constructor(
    private val uploadTaskDao: UploadTaskDao
) {

    /**
     * 获取所有上传任务
     */
    fun getAllUploadTasks(): Flow<List<UploadTask>> {
        return uploadTaskDao.getAllUploadTasks().map { entities ->
            entities.map { it.toUploadTask() }
        }
    }

    /**
     * 插入上传任务
     */
    suspend fun insertUploadTask(uploadTask: UploadTask) {
        uploadTaskDao.insertUploadTask(uploadTask.toUploadTaskEntity())
    }

    /**
     * 更新上传任务
     */
    suspend fun updateUploadTask(uploadTask: UploadTask) {
        uploadTaskDao.updateUploadTask(uploadTask.toUploadTaskEntity())
    }

    /**
     * 根据ID删除上传任务
     */
    suspend fun deleteUploadTaskById(taskId: String) {
        uploadTaskDao.deleteUploadTaskById(taskId)
    }


    // 扩展函数：将实体模型转换为领域模型
    private fun UploadTaskEntity.toUploadTask(): UploadTask {
        return UploadTask().apply {
            id = this@toUploadTask.id
            fileName = this@toUploadTask.fileName
            fileSize = this@toUploadTask.fileSize
            filePath = this@toUploadTask.filePath
            fileType = this@toUploadTask.fileType
            status = this@toUploadTask.status
            uploadPath = this@toUploadTask.uploadPath
            uploadedSize = this@toUploadTask.uploadedSize
            totalSize = this@toUploadTask.totalSize
            currentChunk = this@toUploadTask.currentChunk
            totalChunk = this@toUploadTask.totalChunk
            labelTip = this@toUploadTask.labelTip
            favorite = this@toUploadTask.favorite
            duration = this@toUploadTask.duration
            albumId = this@toUploadTask.albumId
            mediaId = this@toUploadTask.mediaId
        }
    }

    // 扩展函数：将领域模型转换为实体模型
    private fun UploadTask.toUploadTaskEntity(): UploadTaskEntity {
        return UploadTaskEntity(
            id = this.id,
            fileName = this.fileName,
            fileSize = this.fileSize,
            filePath = this.filePath,
            fileType = this.fileType,
            status = this.status,
            uploadPath = this.uploadPath,
            uploadedSize = this.uploadedSize,
            totalSize = this.totalSize,
            currentChunk = this.currentChunk,
            totalChunk = this.totalChunk,
            labelTip = this.labelTip,
            favorite = this.favorite,
            duration = this.duration,
            albumId = this.albumId,
            mediaId = this.mediaId,
            userId = this.userId
        )
    }
}